package com.bmth.alise.client;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import us.codecraft.webmagic.Spider;

public class MessageReceiver implements Runnable {

	public void start() {
		new Thread(this, "Name-Receiver").start();
	}

	private String url;
	private final String QUEUE;
	private Spider spider;

	public MessageReceiver(String url, String queue, Spider spider) {
		this.url = url;
		this.QUEUE = queue;
		this.spider = spider;
	}

	@Override
	public void run() {
		try {
			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
			Connection connection = connectionFactory.createConnection();

			connection.start();
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(QUEUE);
			MessageConsumer consumer = session.createConsumer(destination);

			while (true) {

				Message message = consumer.receive(1000);
				if ("close".equals(message)) {
					consumer.close();
					session.close();
					connection.close();
				}
				if (message != null) {
					try {
						if (message instanceof TextMessage) {
							TextMessage txtMsg = (TextMessage) message;
							System.out.println("receive >> " + txtMsg.getText());
							spider.addUrl(txtMsg.getText());
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}